{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 创建shp文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "#coding=utf-8\n",
    "from osgeo import ogr,gdal,osr #导入ogr包\n",
    "import os\n",
    "gdal.SetConfigOption(\"GDAL_FILENAME_IS_UTF8\", \"YES\") #中文乱码问题\n",
    "gdal.SetConfigOption(\"SHAPE_ENCODING\", \"GBK\")\n",
    "#set the proj dir 投影数据目录设置\n",
    "os.environ['PROJ_LIB'] = r'.venv\\Lib\\site-packages\\osgeo\\data\\proj'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# driver"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "outDriver = ogr.GetDriverByName(\"ESRI Shapefile\") #数据驱动类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# datasource"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<osgeo.ogr.DataSource; proxy of <Swig Object of type 'OGRDataSourceShadow *' at 0x0000028A745EC870> >\n"
     ]
    }
   ],
   "source": [
    "\n",
    "outShapefile = r\"data/hubu_create.shp\" #文件名\n",
    "if os.path.exists(outShapefile): #判断是否已存在，如果有则删除\n",
    "        outDriver.DeleteDataSource(outShapefile)\n",
    "ds =outDriver.CreateDataSource(outShapefile) #创建数据源\n",
    "print(ds)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# layer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\GitHub\\py313Env\\.venv\\Lib\\site-packages\\osgeo\\osr.py:410: FutureWarning: Neither osr.UseExceptions() nor osr.DontUseExceptions() has been explicitly called. In GDAL 4.0, exceptions will be enabled by default.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "targetRS = osr.SpatialReference() #定义空间参考对象\n",
    "# http://epsg.io/  #https://epsg.org/search/by-name\n",
    "#用EPSG代号定义空间参考信息，4326为WGS1984地理坐标系\n",
    "targetRS.ImportFromEPSG(4326)\n",
    "#创建图层，图层名为：hubu_create，空间参考为：EPSG4326，图层类型为：多边形\n",
    "outLayer=ds.CreateLayer('hubu_create',targetRS,geom_type=ogr.wkbPolygon)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# feature"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## field"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fieldName1 = 'name'\n",
    "fieldType1 = ogr.OFTString\n",
    "fieldValue1 = 'hubu'\n",
    "fieldName2 = 'code'\n",
    "fieldType2 = ogr.OFTString\n",
    "fieldValue2 = 'B001B06EAF'\n",
    "# create a field\n",
    "nameField = ogr.FieldDefn(fieldName1, fieldType1)\n",
    "codeField = ogr.FieldDefn(fieldName2, fieldType2)\n",
    "outLayer.CreateField(nameField)\n",
    "outLayer.CreateField(codeField)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# geometry"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "POLYGON Z ((114.322850704193 30.5789255121178 0,114.32443857193 30.5775584607746 0,114.324696063995 30.5772998272713 0,114.324953556061 30.576727136345 0,114.325683116913 30.5751383631659 0,114.327099323273 30.5737527839127 0,114.327549934387 30.5736049876239 0,114.3283867836 30.5739190544683 0,114.329137802124 30.5738636309814 0,114.329459667206 30.5734387165299 0,114.331347942352 30.5742146458633 0,114.329588413239 30.5781311467912 0,114.332120418549 30.5800893379375 0,114.331583976746 30.5812716228789 0,114.332463741302 30.5817519220182 0,114.331755638123 30.5833960049056 0,114.329845905304 30.5850954770106 0,114.322850704193 30.5789255121178 0))\n"
     ]
    }
   ],
   "source": [
    "# Create test polygon\n",
    "ring = ogr.Geometry(ogr.wkbLinearRing) #线\n",
    "ring.AddPoint(114.32285070419314,30.57892551211783)\n",
    "ring.AddPoint(114.32443857192993,30.577558460774558)\n",
    "ring.AddPoint(114.32469606399536,30.577299827271318)\n",
    "ring.AddPoint(114.32495355606078,30.576727136345028)\n",
    "ring.AddPoint(114.32568311691284,30.575138363165852)\n",
    "ring.AddPoint(114.32709932327275,30.573752783912695)\n",
    "ring.AddPoint(114.32754993438719,30.57360498762394)\n",
    "ring.AddPoint(114.32838678359985,30.573919054468277)\n",
    "ring.AddPoint(114.32913780212402,30.57386363098143)\n",
    "ring.AddPoint(114.32945966720581,30.5734387165299)\n",
    "ring.AddPoint(114.33134794235232,30.574214645863282)\n",
    "ring.AddPoint(114.32958841323855,30.57813114679117)\n",
    "ring.AddPoint(114.33212041854858,30.580089337937473)\n",
    "ring.AddPoint(114.33158397674563,30.581271622878855)\n",
    "ring.AddPoint(114.33246374130249,30.58175192201823)\n",
    "ring.AddPoint(114.33175563812257,30.583396004905637)\n",
    "ring.AddPoint(114.32984590530397,30.585095477010636)\n",
    "ring.AddPoint(114.32285070419314,30.57892551211783)\n",
    "poly = ogr.Geometry(ogr.wkbPolygon)#多边形\n",
    "poly.AddGeometry(ring) #将线连成多边形\n",
    "print(poly)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## feature & set values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data/hubu_create.shphas been created!\n"
     ]
    }
   ],
   "source": [
    " # Create the feature\n",
    "layerDefn = outLayer.GetLayerDefn()\n",
    "outFeature = ogr.Feature(layerDefn)\n",
    "outFeature.SetGeometry(poly)\n",
    "outFeature.SetField(fieldName1, fieldValue1)\n",
    "outFeature.SetField(fieldName2, fieldValue2)\n",
    "outLayer.CreateFeature(outFeature)\n",
    "ds.Destroy()\n",
    "print(outShapefile + 'has been created!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 测试打开创建数据并输出信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of features is: 1\n",
      "Extent is: (114.32285070419314, 114.33246374130249, 30.5734387165299, 30.585095477010636)\n",
      "SpatialRef is: GEOGCS[\"WGS 84\",\n",
      "    DATUM[\"WGS_1984\",\n",
      "        SPHEROID[\"WGS 84\",6378137,298.257223563,\n",
      "            AUTHORITY[\"EPSG\",\"7030\"]],\n",
      "        AUTHORITY[\"EPSG\",\"6326\"]],\n",
      "    PRIMEM[\"Greenwich\",0,\n",
      "        AUTHORITY[\"EPSG\",\"8901\"]],\n",
      "    UNIT[\"degree\",0.0174532925199433,\n",
      "        AUTHORITY[\"EPSG\",\"9122\"]],\n",
      "    AXIS[\"Latitude\",NORTH],\n",
      "    AXIS[\"Longitude\",EAST],\n",
      "    AUTHORITY[\"EPSG\",\"4326\"]]\n",
      "GetMetadata is: {'DBF_DATE_LAST_UPDATE': '2024-10-29'}\n",
      "GetLayerDefn is: ['AddFieldDefn', 'AddGeomFieldDefn', 'DeleteGeomFieldDefn', 'Destroy', 'GetFieldCount', 'GetFieldDefn', 'GetFieldIndex', 'GetGeomFieldCount', 'GetGeomFieldDefn', 'GetGeomFieldIndex', 'GetGeomType', 'GetName', 'GetReferenceCount', 'IsGeometryIgnored', 'IsSame', 'IsStyleIgnored', 'SetGeomType', 'SetGeometryIgnored', 'SetStyleIgnored', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__firstlineno__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__static_attributes__', '__str__', '__subclasshook__', '__swig_destroy__', '__weakref__', 'this', 'thisown']\n"
     ]
    }
   ],
   "source": [
    "# outShapefile = r\"data\\hubu_create.shp\"\n",
    "driver = ogr.GetDriverByName('ESRI Shapefile')\n",
    "ds = driver.Open(outShapefile, 0) # 0 means read-only. 1 means writeable.\n",
    "layer = ds.GetLayer()\n",
    "featureCount = layer.GetFeatureCount()\n",
    "print(\"Number of features is: %d\" %featureCount) #要素个数\n",
    "print(\"Extent is: {}\".format(layer.GetExtent())) #空间范围\n",
    "print(\"SpatialRef is: {}\".format(layer.GetSpatialRef())) #空间参考信息\n",
    "print(\"GetMetadata is: {}\".format(layer.GetMetadata())) #元数据信息\n",
    "print(\"GetLayerDefn is: {}\".format(dir(layer.GetLayerDefn())))\n",
    "ds.Destroy()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
